//
//  YAYIServiceContentController.m
//  YAYIDoctor
//
//  Created by hxp on 16/5/5.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIServiceContentController.h"
#import "YAYIServiceContentCell.h"
#import "YAYIServicePriceCell.h"
#import "YAYIServiceTagModel.h"
#import "YAYIServiceModel.h"

#define TableviewTagCategory 100
#define TableviewTagServiceItem 200


@interface YAYIServiceContentController ()<UITableViewDelegate,UITableViewDataSource, UIAlertViewDelegate>

@property (nonatomic,weak) UITableView *categoryTableView;
@property (nonatomic,weak) UITableView *serviceItemTableView;
@property (nonatomic,strong)UIButton *addBtn;

@property (nonatomic, assign) NSInteger curSelectedCategory;
@property (nonatomic,strong)NSMutableArray *categoryArray;
@property (nonatomic,strong)NSMutableArray *serviceItemArray;
@property (nonatomic,strong)NSMutableArray *selectedArray;

@property (nonatomic, assign) NSInteger selectedCount;

@end

@implementation YAYIServiceContentController


- (void)setSelectedCount:(NSInteger)selectedCount
{
    
    _selectedCount = selectedCount;
    if(selectedCount > 0) {

        [self.addBtn setTitle:[NSString stringWithFormat:@"添加(%zd)",selectedCount] forState:UIControlStateNormal];
    }else{
        [self.addBtn setTitle:@"添加" forState:UIControlStateNormal];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.categoryArray = [NSMutableArray array];
    self.serviceItemArray = [NSMutableArray array];
    self.selectedArray = [NSMutableArray array];
    
    [self setupNav];
    [self setupSubView];

    [self getCategory];
    
}


-(void)setupNav
{
    self.addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addBtn setTitle:@"添加" forState:UIControlStateNormal];
    [self.addBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    self.addBtn.frame = CGRectMake(0, 0, 60, 30);
    self.addBtn.titleLabel.font = [UIFont systemFontOfSize:font18];
    self.addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.addBtn addTarget:self action:@selector(onAddBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.addBtn];
    self.navigationItem.rightBarButtonItem = item;
}


-(void)setupSubView
{
    // 创建左边类别tableview
    UITableView *categoryTableView = [UITableView new];
    categoryTableView.backgroundColor = [UIColor clearColor];
    categoryTableView.delegate = self;
    categoryTableView.tag = TableviewTagCategory;
    categoryTableView.dataSource = self;
    categoryTableView.showsVerticalScrollIndicator = NO;
    categoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:categoryTableView];
    self.categoryTableView = categoryTableView;

    [categoryTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.top.equalTo(@(0));
        make.size.mas_equalTo(CGSizeMake(120, SCREEN_height - 64));
    }];
        
    // 创建右边服务项目tableview
    UITableView *serviceItemTableView = [[UITableView alloc] init];
    serviceItemTableView.tag = TableviewTagServiceItem;
    serviceItemTableView.backgroundColor = [UIColor clearColor];
    serviceItemTableView.delegate = self;
    serviceItemTableView.dataSource = self;
    serviceItemTableView.showsVerticalScrollIndicator = NO;
    serviceItemTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:serviceItemTableView];
    self.serviceItemTableView = serviceItemTableView;
    
    [serviceItemTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(120);
        make.top.mas_equalTo(64);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 120, SCREEN_height - 64));
    }];
    
}


#pragma mark - 点击事件
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)onAddBtnClick:(UIButton *)sender
{
    
    if (self.selectedCount == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您还没有选择任何项目，确定提交？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        return;
    }
    
    [self back];
    
    // 获取被选中的item
    for (YAYIServiceTagModel *tagModel in self.categoryArray) {
        
        for (YAYIServiceModel *serviceItemModel in tagModel.serviceItemArray) {
            
            if (serviceItemModel.isSelected) {
                
                [self.selectedArray addObject:serviceItemModel];
            }
        }
    }
    
    // 点击添加
    if (_delegate && [_delegate respondsToSelector:@selector(serviceChecked:)]) {
        [_delegate serviceChecked:self.selectedArray];
    }
}



#pragma mark - 获取数据
/**
 *  获取类别
 */
-(void)getCategory{
    
    [YAYINetWorking getWithURL:querry_service_tag param:@{@"hospitalid":self.hospitalid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"类别：%@", dict);
        
        if ([dict[@"status"] isEqualToString:@"success"]) {
            NSArray *data = dict[@"data"];
            for (NSDictionary *obj in data) {
                
                YAYIServiceTagModel *model = [YAYIServiceTagModel new];
                [model setValuesForKeysWithDictionary:obj];
                [self.categoryArray addObject:model];
            }
            
            [self.categoryTableView reloadData];
            if (self.categoryArray.count > 0) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [self tableView:self.categoryTableView didSelectRowAtIndexPath:indexPath];
                [self.categoryTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            }
        }
    }];
}

/**
 *  获取项目
 */
-(void)getServiceItem:(NSString *)tagid index:(NSInteger)index
{
    if (tagid == nil) {
        return;
    }
    
    YAYIServiceTagModel *tagModel = self.categoryArray[index];
    if (tagModel.serviceItemArray.count > 0) {
        [self.serviceItemTableView reloadData];
        return;
    }
    
    [YAYINetWorking getWithURL:querry_service param:@{@"tagid": tagid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if ([dict[@"status"] isEqualToString:@"success"]) {
            
//            [self.datamuCheckAry removeAllObjects];
            
            NSArray *data = dict[@"data"];
            for (NSDictionary *obj in data) {
                
                YAYIServiceModel *model = [YAYIServiceModel new];
                [model setValuesForKeysWithDictionary:obj];
                
                [tagModel.serviceItemArray addObject:model];
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setValue:@"NO" forKey:@"checked"];
//                [self.datamuCheckAry addObject:dict];
            }
            
            YAYILog(@"tagModel.serviceItemArray:%zd", tagModel.serviceItemArray.count);
            [self.serviceItemTableView reloadData];
        }
    }];
}


#pragma mark - 代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == TableviewTagCategory) { // 类别tableview
        
        return self.categoryArray.count;
    }else{ // 服务项目tableview
        
        if (self.categoryArray.count == 0) {
            return 0;
        }
        
        YAYIServiceTagModel *tagModel = self.categoryArray[self.curSelectedCategory];
        return tagModel.serviceItemArray.count;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == TableviewTagCategory) { // 类别tableview
        
        return 44;
    }else{ // 服务项目tableview
        
        return 66;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == TableviewTagCategory) { // 类别tableview
        
        YAYIServiceContentCell *cell = [YAYIServiceContentCell cellWith:tableView];
        cell.model = self.categoryArray[indexPath.row];
        
        return cell;
    }else{ // 服务项目tableview
        
        YAYIServicePriceCell *cell = [YAYIServicePriceCell cellWith:tableView];
        
        YAYIServiceTagModel *tagModel = self.categoryArray[self.curSelectedCategory];
        YAYIServiceModel *model = tagModel.serviceItemArray[indexPath.row];
        cell.model = model;
        cell.isSelected = model.isSelected;
        return cell;
    }
    
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (tableView.tag == TableviewTagCategory) { // 类别tableview
        
        self.curSelectedCategory = indexPath.row;
        NSString *tagID = [self.categoryArray[indexPath.row] id];
        [self getServiceItem:tagID index:indexPath.row];
    }else{ // 服务项目tableview
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        YAYIServiceTagModel *tagModel = self.categoryArray[self.curSelectedCategory];
        YAYIServiceModel *model = tagModel.serviceItemArray[indexPath.row];
        model.isSelected = !model.isSelected;
        
        YAYIServicePriceCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.isSelected = model.isSelected;
        
        if (model.isSelected) {
            self.selectedCount++;
        }else{
            self.selectedCount--;
        }
    }
}


#pragma mark UIAlertView代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


@end
